package com.lifesea.notify.push;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import com.lifesea.base.entity.PushAppEnums;
import com.lifesea.base.entity.PushRequest;
import com.lifesea.base.entity.PushResponse;
import com.lifesea.base.entity.ResultEnum;
import com.lifesea.commons.exception.ErrorCodeConst;
import com.lifesea.commons.exception.ErrorCodeException;
import com.lifesea.conifg.GeXinConfig;
import com.lifesea.model.SysDeviceIdentify;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 安卓Push
 * User: chendw
 * Date: 2016/7/19 10:52
 * To change this template use File | Settings | File Templates.
 */
@Component
public class AndroidPushService implements IPushService {

    private final Logger logger = LoggerFactory.getLogger(AndroidPushService.class);

    /**
     * 居民端
     */
    private IGtPush residentPush = new IGtPush(GeXinConfig.HOST, GeXinConfig.RESIDENT_APPKEY, GeXinConfig.RESIDENT_MASTERSECRET);

    /**
     * 家医端
     */
    private IGtPush familyDoctorPush = new IGtPush(GeXinConfig.HOST, GeXinConfig.FAMILYDOCTOR_APPKEY, GeXinConfig.FAMILYDOCTOR_MASTERSECRET);

    /**
     * 会诊医生端
     */
    private IGtPush assistantReferralPush = new IGtPush(GeXinConfig.HOST, GeXinConfig.ASSISTANT_REFERRAL_APPKEY, GeXinConfig.ASSISTANT_REFERRAL_MASTERSECRET);

    /**
     * 转诊助手端
     */
    private IGtPush majorDoctorPush = new IGtPush(GeXinConfig.HOST, GeXinConfig.MAJOR_DOCTOR_APPKEY, GeXinConfig.MAJOR_DOCTOR_MASTERSECRET);

    @Override
    public PushResponse send(PushRequest pushRequest, SysDeviceIdentify deviceIdentify) {
        String appid;
        String appkey;
        IGtPush push;

        if (StringUtils.equals(PushAppEnums.resident.value(), deviceIdentify.getAppcode())) {
            appid = GeXinConfig.RESIDENT_APPID;
            appkey = GeXinConfig.RESIDENT_APPKEY;
            push = residentPush;
        } else if (StringUtils.equals(PushAppEnums.family_doctor.value(), deviceIdentify.getAppcode())) {
            appid = GeXinConfig.FAMILYDOCTOR_APPID;
            appkey = GeXinConfig.FAMILYDOCTOR_APPKEY;
            push = familyDoctorPush;
        } else if (StringUtils.equals(PushAppEnums.major_doctor.value(), deviceIdentify.getAppcode())) {
            appid = GeXinConfig.MAJOR_DOCTOR_APPID;
            appkey = GeXinConfig.MAJOR_DOCTOR_APPKEY;
            push = majorDoctorPush;
        } else if (StringUtils.equals(PushAppEnums.assistant_referral.value(), deviceIdentify.getAppcode())) {
            appid = GeXinConfig.ASSISTANT_REFERRAL_APPID;
            appkey = GeXinConfig.ASSISTANT_REFERRAL_APPKEY;
            push = assistantReferralPush;
        } else {
            throw new ErrorCodeException(ErrorCodeConst.GLOBAL_REQUEST_ERROR, String.format("未定义的AppCode[%s]", deviceIdentify.getAppcode()));
        }

        //通知透传模板
        TransmissionTemplate template = transmissionTemplateDemo(appid, appkey, pushRequest);
        ListMessage message = new ListMessage();
        message.setData(template);

        //设置消息离线，并设置离线时间
        message.setOffline(true);
        //离线有效时间，单位为毫秒，可选
        message.setOfflineExpireTime(24 * 1000 * 3600);

        //配置推送目标
        List targets = new ArrayList();

        Target target = new Target();
        target.setAppId(appid);
        target.setClientId(deviceIdentify.getIdentify());
        targets.add(target);

        //获取taskID
        String taskId = push.getContentId(message);
        //使用taskID对目标进行推送
        IPushResult ret = push.pushMessageToList(taskId, targets);

        PushResponse response = new PushResponse();
        if (StringUtils.equals(MapUtils.getString(ret.getResponse(), "result"), "ok")) {
            response.setCode(ResultEnum.SUCCESS);
        } else {
            response.setMsg(JSON.toJSONString(ret.getResponse()));
            response.setCode(ResultEnum.FAILD);
        }
        logger.info("个推送返回data={}", JSON.toJSONString(ret));

        return response;
    }

    public TransmissionTemplate transmissionTemplateDemo(String appId, String appKey, PushRequest pushRequest) {
        // 透传
        TransmissionTemplate template = new TransmissionTemplate();
        // 设置APPID与APPKEY
        template.setAppId(appId);
        template.setAppkey(appKey);
        // 透传消息设置
        template.setTransmissionType(2);
        String jsonString = JSON.toJSONString(pushRequest);
        JSONObject json = JSON.parseObject(jsonString);

        json.put("ref_id", pushRequest.getRefId());// 兼容老版本
        json.put("ref_type", pushRequest.getRefId());// 兼容老版本

        template.setTransmissionContent(json.toJSONString());
        return template;
    }

}
